#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>

#include "nocopy.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace log_ns;

static const int gblcklog = 8;

int main(int argc, char* args[])
{
    if(argc != 3)
    {
        std::cout<<"Usage: ./tcpclient -sockip -sockport"<<std::endl;
        exit(0);
    }
    std::string ip = args[1];
    uint16_t port = std::stoi(args[2]);

    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in addr;
    addr.sin_port = htons(port);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(ip.c_str());
    socklen_t len =sizeof(addr);

    int n = ::connect(sockfd, (struct sockaddr*)&addr, len);
    if(n < 0)
    {
        LOG(FATAL, "Connect error\n");
        exit(3);
    }

    while(1)
    {
        std::string message;
        std::cout<<"Please Enter# ";
        std::cin>>message;
        write(sockfd, message.c_str(), message.size());

        char echo_buffer[1024];
        n = ::read(sockfd, echo_buffer, sizeof(echo_buffer)-1);
        if(n > 0)
        {
            echo_buffer[n]=0;
            std::cout<<echo_buffer<<std::endl;
        }
        else if(n == 0)
        {
            std::cout<<"server quit"<<std::endl;
            break;
        }
        else
        {
            std::cout<<"read error"<<std::endl;
            break;
        }
    }
    return 0;
}